package com.lpit.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDServiceImpl userDService;
//    @Bean
//    public UserDServiceImpl userDServiceImpl(){
//       return new UserDServiceImpl();
//    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                /**
                 * 也可以在请求接口上用 @PreAuthorize(value = "hasRole('管理员')") 注解
                 * */
//                .antMatchers("/admin/userList.html/*/*")//设置这个请求
//                .hasRole("管理员") //只能被这个角色访问

                .antMatchers("/adminLogin.html")
                .permitAll()
                .antMatchers("/data/**")
                .permitAll()
                .antMatchers("user_list.html")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/adminLogin.html")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/zhixing/index.html",true)
                .and()
                .exceptionHandling()
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
                        httpServletRequest.getRequestDispatcher("/adminLogin.html").forward(httpServletRequest,httpServletResponse);
                    }
                })
                .and().csrf().disable()
                .headers()
                .frameOptions()
                .sameOrigin();

//        “X_FRAME_OPTIONS”有三个选项值：
//        DENY ：表示该页面不允许在 frame 中展示，即便是在相同域名的页面中嵌套也不允许
//        SAMEORIGIN ：表示该页面可以在相同域名页面的 frame 中展示
//        ALLOW-FROM uri ：表示该页面可以在指定来源的 frame 中展示
        /*设置为sameOrigin,可以访问frame框架内容（默认是deny）*/
//        http.headers().frameOptions().sameOrigin();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        System.err.println(new BCryptPasswordEncoder().encode("1"));
        System.err.println(userDService+"666666666666");
//        auth.inMemoryAuthentication().passwordEncoder(passwordEncoder()).withUser("1").password(passwordEncoder().encode("1")).roles("admin","user");
        auth.userDetailsService(userDService).passwordEncoder(passwordEncoder());
    }

    /*加密方式*/
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
